import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Card, Avatar, Row, Col, Icon, message, List, Input, Button } from 'antd';
import { formatMoment, getPageQuery } from '../../utils/utils';
import BlankHeader from '../../components/BlankHeader';
import LoadingWrapper from '../../components/LoadingWrapper';
import styles from './index.less';
import { getUid } from '../../utils/token';

const { Item } = List;

@connect(({ picture }) => ({
  pictures: picture.pictures,
}))
export default class Index extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      urlQuery: getPageQuery(),
      likeStatus: 'like-o',
      likeNum: '0',
      favStatus: 'star-o',
      comment: '',
    };
  }

  componentDidMount() {
    const { pictures } = this.props;

    if (pictures.length === 0) {
      this.fetchPictures();
    } else {
      this.prepareState(pictures);
    }
  }

  fetchPictures = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'picture/fetchPictures',
      payload: {
        params: {
          type: 1,
        },
        onSuccess: pictures => {
          this.prepareState(pictures);
        },
      },
    });
  };

  getTargetPicture = pictures => {
    const { urlQuery } = this.state;
    let picture = pictures.filter(item => {
      return item.id === parseInt(urlQuery.pid, 10);
    });
    picture = picture.length === 0 ? null : picture[0];

    return picture;
  };

  handleAddToFavlist = picture => {
    const { dispatch } = this.props;
    if (!picture.isCollected) {
      dispatch({
        type: 'picture/addToFavlist',
        payload: {
          params: {
            params: {
              pid: picture.id,
            },
          },
          onSuccess: () => {
            this.setState({
              favStatus: 'star',
            });
            message.success('收藏成功！');
          },
        },
      });
    }
  };

  prepareState = pictures => {
    const picture = this.getTargetPicture(pictures);
    let likeStatus = 'like-o';
    let favStatus = 'star-o';

    if (picture.isLiked) {
      likeStatus = 'like';
    }
    if (picture.isCollected) {
      favStatus = 'star';
    }

    this.setState({
      likeStatus,
      favStatus,
      likeNum: parseInt(picture.like, 10) === 0 ? '' : `${picture.like}`,
    });
  };

  handleLike = picture => {
    const { likeStatus } = this.state;

    if (picture.isLiked || likeStatus === 'like') {
      message.error('你已经点过赞了！');
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: 'picture/like',
        payload: {
          params: {
            params: {
              uid: getUid(),
              pid: picture.id,
            },
          },
          onSuccess: () => {
            const { likeNum } = this.state;
            this.setState({
              likeStatus: 'like',
              likeNum: likeNum === '' ? 1 : parseInt(likeNum, 10) + 1,
            });
            message.success('点赞成功！');
          },
        },
      });
    }
  };

  handleGoBack = () => {
    const { history } = this.props;
    history.goBack();
  };

  handleUserIndex = uid => {
    const { history } = this.props;
    history.push(`/pic/user?uid=${uid}`);
  };

  handleCommentChange = e => {
    this.setState({ comment: e.target.value });
  };

  handleComment = () => {
    const { dispatch } = this.props;
    const { comment, urlQuery } = this.state;

    dispatch({
      type: 'picture/comment',
      payload: {
        params: {
          params: {
            pid: urlQuery.pid,
            comment,
          },
        },
        onSuccess: () => {
          message.success('评论成功！');
          this.setState({ comment: '' });
          this.fetchPictures();
        },
      },
    });
  };

  render() {
    const { pictures } = this.props;
    const { favStatus, likeNum, likeStatus, comment } = this.state;

    const picture = this.getTargetPicture(pictures);

    return (
      <Fragment>
        <BlankHeader onClick={this.handleGoBack}>{picture && picture.brife}</BlankHeader>
        <LoadingWrapper loading={picture === null} style={{ marginTop: '64px' }}>
          {picture && (
            <Fragment>
              <img style={{ width: '100%' }} src={picture.imgUrl} alt={picture.brife} />
              <Card className={styles.wrapper}>
                <Row>
                  <Col span={4}>
                    <Avatar
                      onClick={() => this.handleUserIndex(picture.uid)}
                      size="large"
                      src={picture.avatar}
                    />
                  </Col>
                  <Col span={14}>
                    <span style={{ fontWeight: 'bold' }}>{picture.author_name}</span>
                  </Col>
                  <Col span={2}>
                    <Icon type={favStatus} onClick={() => this.handleAddToFavlist(picture)} />
                  </Col>
                  <Col span={4}>
                    <Icon type={likeStatus} onClick={() => this.handleLike(picture)} />
                    <span> {likeNum}</span>
                  </Col>
                </Row>
                <Row>
                  <span className={styles.date}>
                    发布于 {formatMoment(moment(picture.updated_at), 'type4')}
                  </span>
                </Row>
              </Card>
              <Card style={{ marginTop: '20px' }}>
                <Row>
                  <Col span={19}>
                    <Input
                      value={comment}
                      onChange={this.handleCommentChange}
                      placeholder="说点什么..."
                    />
                  </Col>
                  <Col offset={1} span={4}>
                    <Button type="primary" onClick={this.handleComment}>
                      评论
                    </Button>
                  </Col>
                </Row>
                <List
                  bordered
                  itemLayout="horizontal"
                  dataSource={picture.comments}
                  className={styles.list}
                  renderItem={item => (
                    <Item>
                      <Item.Meta title={`${item.username}：`} description={item.comment} />
                    </Item>
                  )}
                />
              </Card>
            </Fragment>
          )}
        </LoadingWrapper>
      </Fragment>
    );
  }
}
